﻿using System;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
using VirusCleaner.BugReport;
using VirusCleaner.Center.Froms;

namespace VirusCleaner.Center
{
    static class Program
    {
        #region 加载函数

        /// <summary>
        /// The logging service used for the application.
        /// </summary>
        private static ILogService _logging;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

#if DEBUG
            _logging = new LogService(true);
#else
            _logging = new LogService(false);
#endif
            //获取运行中的实例
            Process instance = RunningInstance();
            if (instance == null)
            {
                //判断是否有参数
                if (args.Length > 0)
                {
                    //如果有参数表示调用模式 显示界面处理
                    //也就是说程序必须有参数调用才可以运行
                    Application.Run(new FrmMain(args, _logging));
                }
                else
                {

#if DEBUG
                    Application.Run(new FrmMain(args, _logging));
#else
                    try
                    {
                        //否则视为用户操作,运行 传递/mian 通知托盘程序 主界面调用
                        Process.Start("VirusCleanerTray.exe", "/main");
                    }
                    catch (Exception ex)
                    {
                        //调用异常
                        MessageBox.Show(
                            VirusCleaner.Language.LanguageString.GetStringA("APP_ERROR"), "ERROR");
                        _logging.WriteException("Message", ex);
                    }
                    finally
                    {
                        //最终将主动退出
                        Application.Exit();
                    }  
#endif
                }

            }
            else
            {
                //如果实例已经存在 显示
                HandleRunningInstance(instance);
            }
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            try
            {
                // Last ditch attempt to write the exception information to the log service.
                _logging.WriteException("Unhandled exception", e.Exception);
            }
            catch
            {
                //System.Windows.Forms.MessageBox.Show(
                //    Properties.Resources.UnhandledException,
                //    Properties.Resources.UnhandledExceptionCaption,
                //    MessageBoxButtons.OK,
                //    MessageBoxIcon.Error,
                //    MessageBoxDefaultButton.Button1,
                //    0);
            }


        }
        #endregion
        #region 处理函数
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;

        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            // ReSharper disable PossibleNullReferenceException
            return
                processes.Where(process => process.Id != current.Id).Where(process => current.MainModule != null).
                    FirstOrDefault(
                        process =>
                        Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
                            // ReSharper restore PossibleNullReferenceException
                        current.MainModule.FileName);
        }

        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            SetForegroundWindow(instance.MainWindowHandle);
        }
        #endregion
    }
}